<template>
  <div class="tabs">
    <div class="tabs-nav" ref="container">
      <div
        class="tabs-nav-item"
        :class="{ active: selected === item.label, disabled: item.disabled }"
        v-for="(item, index) in tabsList"
        :key="index"
        :ref="
          (el) => {
            if (item.label === selected) selectedItem = el;
          }
        "
        @click="select(item)"
      >
        {{ item.label }}
      </div>
      <div class="tabs-nav-indicator" ref="indicator"></div>
    </div>
    <div class="tabs-content">
      <component :is="currentTabs" :key="selected"></component>
    </div>
  </div>
</template>

<script lang="ts">
import Tab from "./Tab.vue";
import { computed, ref, watchEffect, onMounted } from "vue";
export default {
  props: {
    selected: {
      type: String,
    },
  },
  setup(props, context) {
    const selectedItem = ref<HTMLDivElement>(null);
    const indicator = ref<HTMLDivElement>(null);
    const container = ref<HTMLDivElement>(null);
    const defaults = context.slots.default();
    defaults.forEach((item) => {
      if (item.type != Tab) {
        console.log("子组件类型必须为Tab");
      }
    });
    onMounted(() => {
      watchEffect(() => {
        const { width } = selectedItem.value.getBoundingClientRect();
        indicator.value.style.width = width + "px";
        const { left: left1 } = container.value.getBoundingClientRect();
        const { left: left2 } = selectedItem.value.getBoundingClientRect();
        const left = left2 - left1;
        indicator.value.style.left = left + "px";
      });
    });
    const currentTabs = computed(() => {
      return defaults.find((item) => props.selected === item.props.label);
    });
    const tabsList = defaults.map((item) => {
      return {
        label: item.props.label,
        disabled: item.props.disabled != undefined ? true : false,
      };
    });
    const select = (item) => {
      if (item.disabled) return;
      context.emit("update:selected", item.label);
    };
    return {
      selectedItem,
      indicator,
      container,
      currentTabs,
      tabsList,
      select,
    };
  },
};
</script>
<style lang="scss">
$blue: #40a9ff;
$color: #333;
$border-color: #d9d9d9;
$disbaled-color: #c0c4cc;

.tabs {
  &-nav {
    display: flex;
    color: $color;
    border-bottom: 1px solid $border-color;
    position: relative;

    &-item {
      padding: 8px 0;
      margin: 0 16px;
      cursor: pointer;

      &:first-child {
        margin-left: 0;
      }

      &.active {
        color: $blue;
      }
      &.disabled {
        color: $disbaled-color;
        cursor: not-allowed;
      }
    }

    &-indicator {
      position: absolute;
      height: 3px;
      background: $blue;
      left: 0;
      bottom: -1px;
      width: 100px;
      transition: all 250ms;
    }
  }

  &-content {
    padding: 8px 0;
  }
}
</style>
